
from port_item import PortItem
from net import Net
from cell import Cell

import util

class Module:
    
    def __init__(self,name="") -> None:
        self.bit_index = 2
        self.all_ports = []
        self.cells = {}
        self.nets = []
        self.name = name
        pass
    
    def add_port(self,port:PortItem):
        # for pin in port.get_all_pins():
        #     pin.set_id(self.bit_index)
        #     self.bit_index+=1
        self.all_ports.append(port)
        port.set_parent(self)

        pass
    
    def add_cell(self, cell:Cell):
        self.cells[cell.get_name()] = cell

    def add_net(self, net:Net):
        # 给net设置bits
        for i in range(net.get_pin_count()):
            net.set_bit(self.bit_index,i)
            self.bit_index+=1
        self.nets.append(net)
    # def add_net_and_set_bits(self,net:Net):
    #     for i in range(net.get_pin_count()):
    #         net.set_bit(i,self.bit_index)
    #         self.bit_index+=1
    #     self.nets.append(net)
            
    
    def get_port(self,port_name):
        for port in self.all_ports:
            if port.name ==port_name:
                return port
        exit(-1)
    def get_all_ports(self):
        return self.all_ports
    def get_all_cells(self):
        return self.cells
    def get_all_nets(self):
        return self.nets
    
    # def gen_module(self):
    #     # 给所有pin id赋值
    #     pin_index = 2
    #     for port in self.all_ports:
    #         for pin in port.get_all_pins():
    #             pin.set_id(pin_index)
    #             pin_index+=1
    def get_name(self):
        return self.name
    
    # 某些cell的port部分pin需要接到空net上
    def set_cell_port_empty(self,cell:Cell,port_name:str,ids):
        # 新建net，bist位数与ids长度相等
        net = Net(name= port_name.lower()+"_"+util.generate_16_char_uuid(),pin_count=len(ids))
        self.add_net(net)
        # 绑定端口
        for index, pin_id in enumerate(ids):
            cell.get_port(port_name).get_pin_by_index(pin_id).set_bit(net.get_bit(index))


